package mutilthread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description: reentrantLock 用法
 * User: Li_yizYa
 * Date: 2025—04—08
 * Time: 17:36
 */
public class Demo26 {
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        // ReentrantLock locker = new ReentrantLock();
        Semaphore semaphore = new Semaphore(1); // 值为 1 的信号量相当于“锁”

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
//                locker.lock();
                try {
                    semaphore.acquire();
                    count++;
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

//                locker.unlock();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
//                locker.lock();
                try {
                    semaphore.acquire();
                    count++;
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
//                locker.unlock();
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count = " + count);
    }
}
